package com.example.wificovv2;


import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.maps.MapActivity;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.database.myDBHelper;
import com.example.wificov.SamplingPowPic;
import android.location.Address;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.widget.TextView;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.view.*;
import android.view.View.OnClickListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.widget.Button;


public class SeekAp extends Activity implements LocationListener {
	myDBHelper db;
	
	GoogleMap myMap;
	UiSettings uisetting;
	LatLng myLatlng;
	int locFlag = 1;
	private LocationManager locationManager;
	static private Location orgLoc;
	private Location currentLoc;
	private String provider;
	float x0 = 0f;
	float y0=0f;
	float xtemp=0f;
	float ytemp=0f;
	float L =0F;
	float xAp, yAp;
	int idAP;
  	
	//cac doi tuong	
	private TextView latituteField, longitudeField, updateTime, distance1, distance2, comparewithinput;
	private TextView radius, angle;
	Button btn1, btn2, btn3;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		db = new myDBHelper( this );
		
		FragmentManager myFragmentManager = getFragmentManager();
        MapFragment myMapFragment = (MapFragment)myFragmentManager.findFragmentById(R.id.mapfrag);
        myMap = myMapFragment.getMap();
        
        // Getting reference to SupportMapFragment of the activity_main
        MapFragment fm = (MapFragment)getFragmentManager().findFragmentById(R.id.mapfrag);
 
        // Getting Map for the SupportMapFragment
        myMap = fm.getMap();
 
        // Enable MyLocation Button in the Map
        myMap.setMyLocationEnabled(true);
        this.myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        this.uisetting = myMap.getUiSettings();
        this.uisetting.setZoomControlsEnabled( false );
        
        idAP = Integer.parseInt(SeekAp.this.getIntent().getStringExtra("APID"));
		
        //Lấy toạ độ của AP cần khảo sát từ database
	  	String[] size = db.getAPpos(idAP);
	  	xAp = Float.parseFloat(size[0]);
	  	yAp = Float.parseFloat(size[1]);	  	
        
        this.myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(xAp, yAp), 14));
        MarkerOptions marker = new MarkerOptions();
        LatLng latlng = new LatLng(xAp, yAp);
		marker.position(latlng);
		marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
		myMap.addMarker(marker);
        
        myMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
			
			@Override
			public void onMyLocationChange(Location arg0) {
				myLatlng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
				if(locFlag == 1)
				{
					myMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatlng, 16));
					locFlag = 0;
				}
			}
		});

		latituteField = (TextView) findViewById(R.id.latitude);
		longitudeField = (TextView) findViewById(R.id.idlongtitude);
		updateTime = (TextView) findViewById(R.id.updatetime);
		distance1 = (TextView) findViewById(R.id.accuracygps);
		distance2 = (TextView) findViewById(R.id.accuracymean);
		comparewithinput = (TextView) findViewById(R.id.accuaryinnitial);
		radius = (TextView) findViewById(R.id.distance);
		angle = (TextView) findViewById(R.id.ang);
		btn1 = (Button) findViewById(R.id.idstartrootpos);
		btn2 = (Button) findViewById(R.id.notget);
		btn3 = (Button) findViewById(R.id.idsaverootpos);
		
		
		// kich hoat hoat dong lay thong so gps
		latituteField.setText("");
		longitudeField.setText("");
		orgLoc = currentLoc;
		
		btn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		        // Define the criteria how to select the locatioin provider -> use
		        // default
		        Criteria criteria = new Criteria();
		        provider = locationManager.getBestProvider(criteria, false);
		        Location location = locationManager.getLastKnownLocation(provider);

		        // Initialize the location fields
		        if (location != null) {
		        	onLocationChanged(location);
		        } else {
		          latituteField.setText("Location not available");
		          longitudeField.setText("Location not available");
		        }
		        // Lấy giá trị đang được đo, so sánh với dữ liệu trong database và tính sai số
		        xtemp = Float.parseFloat(latituteField.getText()+"");
		        ytemp = Float.parseFloat(longitudeField.getText()+"");		        
		        // Tính khoảng cách hai điểm theo đơn vị m 
		        	
		        	float dist1 = (float) Math.sin((xAp*Math.PI / 180.0) * Math.sin(xtemp*Math.PI / 180.0)
        	                + Math.cos(xAp*Math.PI / 180.0) * Math.cos(xtemp*Math.PI / 180.0)
        	                * Math.cos(yAp - ytemp));
		        	dist1 = (float) Math.acos(dist1);
		        	dist1 = (float) (dist1 * 180.0 / Math.PI);
		        	dist1 = (float) (dist1 * 60 * 1.1515);
		        	String L = String.valueOf(dist1);
		        	radius.setText(L);
		        	float dist2 = (float) Math.sin((xtemp*Math.PI / 180.0) * Math.sin(xtemp*Math.PI / 180.0)
        	                + Math.cos(xtemp*Math.PI / 180.0) * Math.cos(xtemp*Math.PI / 180.0)
        	                * Math.cos(ytemp - yAp));
		        	dist2 = (float) Math.acos(dist1);
		        	dist2 = (float) (dist1 * 180.0 / Math.PI);
		        	dist2 = (float) (dist1 * 60 * 1.1515);
		        	// Tính góc tạo từ điểm đang đo chiếu theo hệ toạ độ với gốc toạ độ là vị trí Access Point
		        	float sinag = (dist2/dist1);
		        	int angle = (int)(Math.asin(sinag));
		        	String A = String.valueOf(angle);
		        	SeekAp.this.angle.setText(A); 	        
			}
		});
		
		
		btn2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SeekAp.this,WSTActivity.class);				
				intent.putExtra("APID", idAP);				
				startActivity(intent);
			}
		});
        
    }
	
		@Override
		protected void onResume() {
	      super.onResume();
	        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
	    }

	    /* Remove the locationlistener updates when Activity is paused */
	    @Override
	    protected void onPause() {
	      super.onPause();
	      locationManager.removeUpdates(this);
	    }
	
	public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			double lat = (double) (location.getLatitude());
			double lng = (double) (location.getLongitude());
		    latituteField.setText(String.valueOf(lat));
		    longitudeField.setText(String.valueOf(lng));
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HH:mm:ss");
		    String currentDateandTime = sdf.format(new Date());
		    updateTime.setText(currentDateandTime);
		    
		    currentLoc = location;
		    if (orgLoc == null)
		    {
		    	orgLoc = location;
		    }
		    float distanceInMet = location.distanceTo(orgLoc);
		    float accuracy = -1;
		    if (location.hasAccuracy())
		    {
		    	accuracy = location.getAccuracy();
		    }
		    //location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results)
		    distance1.setText(String.format("dis = %f ",distanceInMet));
		    distance2.setText(String.format("acc = %f",accuracy));
		}
	    
	
	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	} 
	//Su dung phuong thuc de giu lai trang thai cua Fragment khi chuyen sang view khac va quay lai
	/*@Override
	public void onDestroyView()
	{
	    super.onDestroyView();
	    _savedCameraPosition = _map.getCameraPosition();
	}*/


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		menu.add("Go back home screen")
		.setIntent(new Intent(this, MainActivity.class));
		menu.add("Help")
		.setIntent(new Intent(this, Guide.class));
		menu.add("Sampling power")
		.setIntent(new Intent(this, SamplingPowPic.class));
		menu.add("Sampling pos and bandwidth")
		.setIntent(new Intent(this, SeekAp.class));
		menu.add("View pow map")
		.setIntent(new Intent(this, Displaypow.class));
		menu.add("View band map")
		.setIntent(new Intent(this, Displayband.class));
		menu.add("View wlan map")
		.setIntent(new Intent(this, Wlanmap.class));
		return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId())
    	{
       case R.id.mainscreen:
        //Xử lý tro ve man hinh chinh
    	   break;
        case R.id.guide:
        //xử lý xem thông huong dan
        	break;
        case R.id.samplingpow:
        	break;
        case R.id.samplingband:
        	break;
        case R.id.powermap:
        	break;	
        case R.id.bandwidthmap:
        	break;	
        case R.id.wlanmap:
        	break;	
        }
        return super.onOptionsItemSelected(item);
        }

}
